"use client";
import * as actions from "@/actions";
import {
  Popover,
  PopoverTrigger,
  PopoverContent,
  Button,
  Input,
  Textarea,
  Chip,
} from "@heroui/react";
import { startTransition, useActionState } from "react";

export default function TopicCreateForm() {
  const [state, formAction,isPending] = useActionState(actions.createTopic, {
    errors: {},
  });
  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) =>{
    e.preventDefault()
    const formData = new FormData(e.target as HTMLFormElement)
    startTransition(() => {
      formAction(formData)
    })
  }
  console.log('state', state);
  return (
    <Popover placement="left">
      <PopoverTrigger>
        <Button color="secondary" variant="bordered" className="block ml-auto">
          Create a Topic
        </Button>
      </PopoverTrigger>
      <PopoverContent>
        <form noValidate onSubmit={handleSubmit}>
          <div className="w-80 flex flex-col gap-4 p-4">
            <h3>Create a Topic</h3>
            <Input
              name="title"
              label="Title"
              placeholder="Title"
              labelPlacement="outside"
              isInvalid={!!state.errors.title}
              errorMessage={state.errors.title?.join(", ")}
            />
            <Textarea
              name="description"
              label="Description"
              placeholder="Description"
              labelPlacement="outside"
              isInvalid={!!state.errors.description}
              errorMessage={state.errors.description?.join(", ")}
            />
              {/* #4 */}
            {state.errors._form ? (
              <Chip variant="bordered" radius="sm" className="max-w-full">
                {state.errors._form.join(", ")}
              </Chip>
            ) : null}
            <Button color="secondary" type="submit"  isLoading={isPending}>
              Submit
            </Button>
          </div>
        </form>
      </PopoverContent>
    </Popover>
  );
}
